
package com.fq.wechat.util;

import com.fq.wechat.constant.MsgKey;
import com.google.common.base.Strings;
import com.google.common.io.CharStreams;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jifang.
 * @since 2016/4/18 16:37.
 */
public class RequestUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * 将微信消息解析成Map
     *
     * @param request
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String, String> parseDataToMap(HttpServletRequest request) {
        Element root;
        String xml = request.getParameter("xml");
        try {
            if (!Strings.isNullOrEmpty(xml)) {
                root = new SAXReader().read(new StringReader(xml)).getRootElement();
            } else {
                String data = CharStreams.toString(new InputStreamReader(request.getInputStream()));
                root = new SAXReader().read(new StringReader(data)).getRootElement();
            }
        } catch (DocumentException | IOException e) {
            LOGGER.error("parse wx xml error", e);
            throw new RuntimeException();
        }

        Map<String, String> resultMap = new HashMap<>();
        List<Element> elements = root.elements();
        for (Element element : elements) {
            String key = element.getName();
            String value = element.getText();
            resultMap.put(key, value);
        }

        return resultMap;
    }

    public static String parseMsgToKey(String wxMsg) {
        if (wxMsg.contains("台灯") && wxMsg.contains("开")) {
            return MsgKey.L_ON;
        } else if (wxMsg.contains("台灯") && wxMsg.contains("关")) {
            return MsgKey.L_OFF;
        } else if (wxMsg.contains("台灯") && wxMsg.contains("状态")) {
            return MsgKey.L_STATUS;
        } else if (wxMsg.contains("湿度")) {
            return MsgKey.H_STATUS;
        } else if (wxMsg.contains("温度")) {
            return MsgKey.T_STATUS;
        } else if (wxMsg.contains("风扇") && wxMsg.contains("开")) {
            return MsgKey.F_ON;
        } else if (wxMsg.contains("风扇") && wxMsg.contains("关")) {
            return MsgKey.F_OFF;
        } else if (wxMsg.contains("风扇") && wxMsg.contains("状态")) {
            return MsgKey.F_STATUS;
        } else if (wxMsg.contains("风扇") && wxMsg.contains("快")) {
            return MsgKey.F_FASTER;
        } else if (wxMsg.contains("风扇") && wxMsg.contains("慢")) {
            return MsgKey.F_SLOWER;
        } else if (wxMsg.contains("绑定")) {
            return MsgKey.D_BINDING;
        } else {
            return MsgKey.E_MANUAL;
        }
    }
}
